﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Kazuku.Core.Models {
	public abstract class ModuleRegistration : AreaRegistration {
		private readonly HashSet<string> _namespaces = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
		public ICollection<string> Namespaces {
			get {
				return _namespaces;
			}
		}
		
		public virtual void RegisterTheViewsInTheEmbeddedViewEngine(Type areaRegistrationType) {
			KazukuVirtualPathProvider.AddResource(
				new AssemblyResource() {
					VirtualPath = GetVirtualPath(AreaName),
					TypeToLocateAssembly = areaRegistrationType,
					Namespace = GetNamespace(areaRegistrationType)
				});
		}

		public string GetNamespace(Type type) {
			return type.Namespace;
		}

		public string GetVirtualPath(string name) {
			return "/areas/" + name.ToLower();
		}

		public Route MapRoute(AreaRegistrationContext context, string url, object defaults) {
			return MapRoute(context, url, defaults, null /* namespaces */);
		}
		
		public Route MapRoute(AreaRegistrationContext context, string url, object defaults, string[] namespaces)
		{
			if (namespaces == null && Namespaces != null) {
				namespaces = Namespaces.ToArray();
			}

			Route route = context.Routes.MapRoute(null, url, defaults, namespaces);
			route.DataTokens["area"] = AreaName;
			route.RouteHandler = new KazukuRouteHandler();

			// disabling the namespace lookup fallback mechanism keeps this area from accidentally picking up
			// controllers belonging to other areas
			bool useNamespaceFallback = (namespaces == null || namespaces.Length == 0);
			route.DataTokens["UseNamespaceFallback"] = useNamespaceFallback;

			return route;
		}
	}
}
